package net.yxsoft.kit.rongzer;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashCodeUtil {
	//生产字符串的基本元素
		protected static char chars[] = 
			{ 
			'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
			'a', 'b', 'c', 'd', 'e', 'f', 'g', 
			'h', 'i', 'j', 'k', 'l', 'm', 'n', 
			'o', 'p', 'q', 'r', 's', 't', 
			'u', 'v', 'w', 'x', 'y', 'z',
			'A', 'B', 'C', 'D', 'E', 'F', 'G', 
			'H', 'I', 'J', 'K', 'L', 'M', 'N', 
			'O', 'P', 'Q', 'R', 'S', 'T', 
			'U', 'V', 'W', 'X', 'Y', 'Z'
			};
		
		/**
		 * 随机生成一个100个字符的字符串，并获取该字符串SHA256算的HASH值
		 * 
		 * @return
		 */
		public static String getSHA256code(){
			String str = "";
			for(int i = 0; i < 100; i++){
				int index = (int) (Math.random() * 62);
				str += chars[index];
			}
			String SHA256Code = getStringHashCodeSHA256(str);
			return SHA256Code;
		}
		
		/**
		 * 计算大文件 md5获取getMD5(); SHA1获取getSha1() CRC32获取 getCRC32()
		 */
		protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
				'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		public static MessageDigest messagedigest = null;
		
		/**
		 * 获取字符串的HashCode SHA256
		 * @param str
		 * @return
		 */
		public static String getStringHashCodeSHA256(String str){
			String returnStr = "";
			try{
				messagedigest = MessageDigest.getInstance("SHA-256");
				byte[] b = str.getBytes();
				messagedigest.update(b);
				returnStr = bufferToHex(messagedigest.digest());
			} catch (NoSuchAlgorithmException e) {
				returnStr = null;
				e.printStackTrace();
			} catch (Exception e){
				returnStr = null;
				e.printStackTrace();
			}
			return returnStr;
		}


		/**
		 * @Description 计算二进制数据
		 * @return String
		 * */
		private static String bufferToHex(byte bytes[]) {
			return bufferToHex(bytes, 0, bytes.length);
		}

		private static String bufferToHex(byte bytes[], int m, int n) {
			StringBuffer stringbuffer = new StringBuffer(2 * n);
			int k = m + n;
			for (int l = m; l < k; l++) {
				appendHexPair(bytes[l], stringbuffer);
			}
			return stringbuffer.toString();
		}

		private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
			char c0 = hexDigits[(bt & 0xf0) >> 4];
			char c1 = hexDigits[bt & 0xf];
			stringbuffer.append(c0);
			stringbuffer.append(c1);
		}
}
